import sys
import re
import time
import json
import pickle,os,random


if os.path.exists("userinfo.txt"):
    filepath = "userinfo.txt"
else:
    open("userinfo.txt", "wb")
    filepath = "userinfo.txt"

# open 和close 是对应的，可以直接用with 语句

if os.path.getsize(filepath):
    f = open(filepath, "rb")
    
    allusers = json.load(f)
else:
    
    allusers = {"admin":{"idCard":"0000","phone":13888888888,"passwd":"123456","money":1000}}
    


		
def firstView():

    print("".center(60,"*"))
    for a in range(2):
        print('*',' '.center(56),'*')
    s1="welcome to SY bank of the ATM"
    print('*',s1.center(56),'*')
    for b in range(2):
        print('*',' '.center(56),'*')
    s2="(1) enter       (2) register"
    print('*',s2.center(56),'*')
    print("".center(60,"*"))    

def choiceView():

    inputView = input("Please make a choice 1 or 2: ")
    print("If you're new one,you will be presented free by 5000$. ")
    if inputView == '1':
        name=enterAdmin()
        sysFuctionView(name)
        

    elif inputView == '2':
        regAdmin()

    else:
        print("it's error,only input 1 or 2")
        quitView()

def enterAdmin():

    print("".center(60,"-"))   
    for i in range(3):
        name=str(input("please input username: "))
        passwd = str(input("please input password: "))
        if name in allusers.keys() and passwd == allusers.get(name)["passwd"]:
            print("it's ok,login is success")
            time.sleep(2)
            return name
            break # return 后面可以用break了
        else:
           print("it's error,please input again.")
    else:
        print(" More than 3 times,it will be exited ")
        quitView()
        exit(0)
    

  

        



def regAdmin():

    print("".center(60,"*"))
    creatUser()

def quitView():
    for a in range(3):
        print("".center(60,"+"))
    s1="See you next time to SY bank of the ATM"
    print('+',s1.center(56),'+')
    for b in range(2):
        print('+',' '.center(56),'+')
    s2="Good Bye"
    print('+',s2.center(56),'+')
    

        



def creatUser():


    name=checkuser()

    passwd=checkPasswd()
    idCard=checkidCard()
    phone=checkphone()

    money= 5000



    allusers.update({name:{"idCard":idCard,"phone":phone,"passwd":passwd,"money":money}})

    print(allusers)
    print("CreatUser is success ,you will be presented free by 5000$.")
    writeDB()
    firstView()

def writeDB():
    with open('userinfo.txt', 'w') as f:
        json.dump(allusers,f)


def checkuser():

    flag=True
    while flag:
        name= input("please input your username :").strip( )
    
        if name in allusers.keys():
            print("name is exist")
            continue
        else:
            print("it's ok")
            flag=False
        
            return name


def checkPasswd():

    flag=True
    while flag:
        passwd = input("please input your passwd 6 digit :")
        newpasswd = input("please input your passwd again :")
        if passwd != newpasswd:
            print("password is different")
            continue
        else:
            pw=re.match(r"^\d{6}$", passwd)
            if pw:
                print("password is ok")
                flag=False
                return passwd
            
            else:
                print("input 6 number ")
                continue

def checkidCard():

    flag=True
    while flag:
        idCard= input("please input your idCard 4 digit :")
        pin=re.match(r"^\d{4}$", idCard)
        if pin:
            print("idCard is ok")
            flag=False
            return idCard
        
        else:
            print("input 4 number ")
            continue

def checkphone():

    flag=True
    while flag:
        phone= input("please input your phone :")
        tel= re.match(r"^1[35789]\d{9}$", phone)
        if tel:
            print("phone is ok")
            flag=False
            return phone
        
        else:
            print("input 11 number for phone")
            continue




def sysFuctionView(name):

    print("".center(60,"*"))
    for a in range(2):
        print('*',' '.center(56),'*')
    s1="(1) Inquiry"        
    s2="(2) Transfer"       
    print('*',s1.center(26),s2.center(29),'*')
    print('*',' '.center(56),'*')
    s3="  (3)Withdraw cash" 
    s4=" (4)Deposit cash"   
    print('*',s3.center(28),s4.center(27),'*')
    print('*',' '.center(56),'*')
    s5="(5) Modify Pin"     
    s6="(6) Quit"           
    print('*',s5.center(27),s6.center(24),' '*3,'*')
    print('*',' '.center(56),'*')
    print("".center(60,"*"))
    option=str(input("please choice one action :"))
    if option == '1':
        Inquiry(name)
    elif option == '2':
        transferMoney(name)
    elif option == '3':
        Withdraw(name)
    elif option == '4':
        Deposit(name)
    elif option == '5':
        changePasswd(name)
    elif option == '6':
        quitView()
    

def checkname(name):

    if name in allusers.keys():
        print("username is ",name)
    else:
        print("username ",name," isn't exist")
    

def Inquiry(name):
    
    checkname(name)
    print("your money is %d"% int(allusers.get(name)["money"]))
    
def Withdraw(name):

    getmoney = int(input("请输入您取款金额："))
    checkname(name)
    nowmoney = int(allusers.get(name)["money"])
    if getmoney > nowmoney:
        print("余额不足，取款失败......")
        return -1
    nowmoney -= getmoney
    allusers.get(name)["money"]=nowmoney
    print("取款成功，您目前余额为：%d" % int(allusers.get(name)["money"]))
    writeDB()

def Deposit(name):

    savemoney = int(input("请输入您存款金额："))
    nowmoney = int(allusers.get(name)["money"])
    nowmoney += savemoney
    allusers.get(name)["money"]=nowmoney
    print("存款成功，您目前余额为：%d" % int(allusers.get(name)["money"]))
    writeDB()

def changePasswd(name):
    oldpasswd = input("请输入密码：")
    if str(oldpasswd)!=allusers.get(name)["passwd"]:
        print("password is wrong")
        return -1
    passwd=checkPasswd()
    allusers.get(name)["passwd"]=passwd
    print("密码修改成功......")
    writeDB()

def transferMoney(name):

    toname = input("请输入您希望转账的账户：")
    checkname(toname)
    tomoney=int(allusers.get(toname)["money"])
    transmoney = int(input("请输入您希望转账的金额："))
    checkname(name)
    
    ownmoney = int(allusers.get(name)["money"])
    if transmoney > ownmoney:
        print("余额不足，转账失败......")
        return -1
    ownmoney -= transmoney
    tomoney += transmoney

    allusers.get(name)["money"] = ownmoney
    allusers.get(toname)["money"] = tomoney
    print("tranfer money is success, username ",toname," money is ",int(allusers.get(toname)["money"]))
    print("tranfer money is success, username ",name," money is ",int(allusers.get(name)["money"]))
    writeDB()


firstView()
choiceView()
f.close

